#include "vm_screen.h"

#include "vm.h"

#include <windows.h>


HBITMAP		vm_screenBMP;
HDC			vm_screenDC;
u32			*vm_buffer;

extern HWND vm_hWnd;
extern int	vm_zoom;



bool vmScr_init()
{
	vm_screenDC = CreateCompatibleDC(GetDC(vm_hWnd));

	BITMAPINFO bmi;
	bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bmi.bmiHeader.biWidth = SCREEN_WIDTH;
	bmi.bmiHeader.biHeight = - SCREEN_COUNT * SCREEN_HEIGHT;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biBitCount = 32;
	bmi.bmiHeader.biCompression = BI_RGB; 
	bmi.bmiHeader.biSizeImage = 0;
	bmi.bmiHeader.biXPelsPerMeter = 0;
	bmi.bmiHeader.biYPelsPerMeter = 0;
	bmi.bmiHeader.biClrUsed = 0;
	bmi.bmiHeader.biClrImportant = 0;

	if ((vm_screenBMP = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void **)&vm_buffer, NULL, 0)) == NULL)
	{	MessageBox (NULL,"Failed to Create Device Independed Bitmap (DIB)", (LPCTSTR)"Error Draw Buffer", MB_OK|MB_ICONEXCLAMATION);
	return false;
	}

	if (SelectObject(vm_screenDC, vm_screenBMP) == NULL)
	{	MessageBox (NULL,"Failed to SelectObject the DIB", (LPCTSTR)"Error Draw Buffer", MB_OK|MB_ICONEXCLAMATION);
	return false;
	}

	return true;
}

void PaintWindow(HDC hdc)
{
	StretchBlt(
		hdc, 
		0, 0, SCREEN_WIDTH * vm_zoom, SCREEN_COUNT * SCREEN_HEIGHT * vm_zoom,
		vm_screenDC,
		0, 0, SCREEN_WIDTH, SCREEN_COUNT * SCREEN_HEIGHT,
		SRCCOPY);
}

void vmScr_flush(u8 bank, VMPtr addr)
{
	vm_setBank(bank);

	u8 data;
	u32 r,g,b;

	u16 pos = 0;

	while (pos < SCREEN_WIDTH * SCREEN_COUNT * SCREEN_HEIGHT)
	{
#if (SCREEN_BPP == 8)
		//read one pixel and decode
		data = vm_readU8(addr++);
		r = (data & 0xE0);
		g = (data & 0x1C) << 3;
		b = (data & 0x03) << 6;

		//write pixel data
		vm_buffer[pos++] = (r<<16) | (g<<8) | b;
#endif //SCREEN_BPP == 8

#if (SCREEN_BPP == 12)
		//read first pixel and decode
		data = vm_readU8(addr++);
		r = (data & 0xF0);
		g = (data & 0x0F);
		data = vm_readU8(addr++);
		b = (data & 0xF0);

		//write first pixel
		vm_buffer[pos++] = (r<<16) | (g<<8) | b;

		//decode second pixel
		r = (data & 0x0F);
		data = vm_readU8(addr++);
		g = (data & 0xF0);
		b = (data & 0x0F);

		//write second pixel
		vm_buffer[pos++] = (r<<16) | (g<<8) | b;
#endif //SCREEN_BPP == 12
	}
}